package cn.wsn2018.tools.dao.impl;

import cn.wsn2018.tools.dao.ProtocolTestDao;
import cn.wsn2018.tools.model.TestReport;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by NZX on 2018/12/28.
 */
@Repository("protocolTestDao")
public class ProtocolTestDaoImpl implements ProtocolTestDao{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveTestReport(TestReport testReport) {
        JSONObject result = JSONObject.fromObject(mongoTemplate.insert(testReport,"protocolTest"));
        String id = result.optString("id");
        if(id!=null&&!"".equals(id)) {
            return id;
        }
        else {
            return null;
        }
    }

    @Override
    public TestReport getTestReport(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        TestReport testReport = mongoTemplate.findOne(query,TestReport.class,"protocolTest");
        return testReport;
    }

    @Override
    public List<TestReport> getTestReports(String username, String pageNum, String pageSize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("username").is(username));
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        int num = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        query.skip((num-1)*size).limit(size);
        List<TestReport> reports = mongoTemplate.find(query,TestReport.class,"protocolTest");
        return reports;
    }

    @Override
    public boolean deleteTestReport(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        JSONObject result = JSONObject.fromObject(mongoTemplate.remove(query,"protocolTest"));
        String count = result.optString("deletedCount");
        if(count!=null&&"1".equals(count)){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int deleteTestReports(List<String> idList) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(idList));
        JSONObject result = JSONObject.fromObject(mongoTemplate.remove(query,"protocolTest"));
        String count = result.optString("deletedCount");
        return Integer.parseInt(count);
    }



}
